package com.project_test.kun.travelling_1st.GoodsDetailActivities.HouseDetail;

import android.graphics.Bitmap;
import android.graphics.drawable.ColorDrawable;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.GridLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;

import com.project_test.kun.travelling_1st.GoodsDetailActivities.HouseDetail.PopupWindowAdapter;
import com.project_test.kun.travelling_1st.HomePage.Util.URL;
import com.project_test.kun.travelling_1st.HomePage.View.GView;
import com.project_test.kun.travelling_1st.HomePage.category.HPHouseDetail;
import com.project_test.kun.travelling_1st.HomePage.category.facility_HPHouseDetail;
import com.project_test.kun.travelling_1st.HomePage.category.mandate_HPHouseDetail;
import com.project_test.kun.travelling_1st.R;
import com.project_test.kun.travelling_1st.Utils.ExpandListView;
import com.squareup.picasso.Picasso;

import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.sharesdk.onekeyshare.OnekeyShare;

/**
 * 房屋详情展示界面
 */
public class House_Detail_Activity extends AppCompatActivity implements ViewPager.OnPageChangeListener, View.OnClickListener {

    private RequestQueue mRequestQueue;
    private  HPHouseDetail houseDetail;//数据类
    private TextView mPrice;
    private ViewPager mPicList;
    private TextView mPicListNum;
    private ImageView[] mImageViews;
    private int picNum;
    private TextView mName;
    private TextView mAddress;
    private TextView mOwner_name;
    private TextView mBathroom_num;
    private TextView mMax_person;
    private TextView mBed_num;
    private Button mContact;
    private TextView mIntro;
    private TextView mMoreIntro;
    private ImageView mOnePic;
    private TextView mChakanDay;
    private TextView mReserve_address;
    private TextView mFangyuanCK;
    private TextView mCheck_time;
    private TextView mOut_time;
    private TextView mDeposit;
    private TextView mMin_Book_days;
    private List<Map<String,String >> mMaps;
    private ExpandListView mMandateList;
    private ImageView mTwoPic;
    private LinearLayout mFacility;
    private TextView mTitle;
    private TextView mDescription;
    private MapView mMap;
    private LatLng mPoint;
    private ImageView mExit;
    private PopupWindow mPopupWindow;
    private ImageView mShare;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_house__detail_);

//        getWindow().setFlags();
        mRequestQueue = Volley.newRequestQueue(this);
        houseDetail =new HPHouseDetail();
        mMaps=new ArrayList<>();
        int hid = getIntent().getIntExtra("hid", 0);
        initView();
        String url= URL.DETAIL_HOUSE_COMMON+URL.DETAIL_HOUSE_HID+hid+URL.DETAIL_HOUSE_LASTCOMMON;
        initData(url);
    }

    private void initData(String url) {
        JsonObjectRequest jsonObjectRequest=new JsonObjectRequest(Request.Method.GET, url, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {

                        try {
                            JSONObject data = response.getJSONObject("data");
                            houseDetail.pashJson(data);
                            Message message = mHandler.obtainMessage();
                            message.what=0;
                            mHandler.sendMessage(message);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(House_Detail_Activity.this, "数据异常,无法访问!", Toast.LENGTH_SHORT).show();
            }
        });
        mRequestQueue.add(jsonObjectRequest);
    }
    private Handler mHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what==0){
                setData();
            }
        }
    };
    public void setData(){

        picNum=houseDetail.getPicLists().size();
        mPrice.setText(houseDetail.getPrice()+"");
        mImageViews=new ImageView[picNum];
        for (int i = 0; i < houseDetail.getPicLists().size(); i++) {
            Map<String, Object> map = houseDetail.getPicLists().get(i);
            String pic_url= (String) map.get("pic_url");
            ImageView imageView=new ImageView(House_Detail_Activity.this);
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            Picasso.with(House_Detail_Activity.this).load(pic_url).into(imageView);
            mImageViews[i]=imageView;
        }
        MyAdapter adapter=new MyAdapter();
        mPicList.setAdapter(adapter);
        mPicListNum.setText(1+"/"+picNum);
        mName.setText(houseDetail.getName());
        mAddress.setText(houseDetail.getAddress_level1()+houseDetail.getAddress_level2()+houseDetail.getAddress_level3()+houseDetail.getAddress_level4());
        mOwner_name.setText(houseDetail.getOwner_name());
        mBathroom_num.setText("房间"+"("+houseDetail.getBathroom_num()+")");
        mMax_person.setText("适合"+houseDetail.getMax_person()+"人");
        mBed_num.setText("床位"+"("+houseDetail.getBed_num()+")");
        mIntro.setText(houseDetail.getIntro()+houseDetail.getRoom_inner_intro()+houseDetail.getTraffic_intro()+houseDetail.getAround_village_intro());
        Picasso.with(this).load(((String)houseDetail.getPicLists().get(3).get("pic_url"))).into(mOnePic);
        //地图
        SetMap(houseDetail.getLat(),houseDetail.getLng());

        mReserve_address.setText(houseDetail.getAddress_level4()+","+houseDetail.getAddress_level3()+","+houseDetail.getAddress_level2()+","+houseDetail.getAddress_level1());
        mCheck_time.setText(houseDetail.getCheck_time()+"");
        mOut_time.setText(houseDetail.getOut_time()+"");
        mDeposit.setText(houseDetail.getDeposit()+"");
        mMin_Book_days.setText(houseDetail.getMin_book_days()+"");
        for (int i = 0; i < houseDetail.getMandates().size(); i++) {
            mandate_HPHouseDetail mandateHpHouseDetail = houseDetail.getMandates().get(i);
            Map<String,String> map=new HashMap<>();
            map.put("name",mandateHpHouseDetail.getName());
            mMaps.add(map);
        }
        SimpleAdapter simpleAdapter=new SimpleAdapter(this,mMaps,R.layout.item_house_detail,new String[]{"name"},new int[]{R.id.text_item_house_detail});
        mMandateList.setAdapter(simpleAdapter);
        Picasso.with(this).load(((String)houseDetail.getPicLists().get(2).get("pic_url"))).into(mTwoPic);
        List<facility_HPHouseDetail> facilitys = houseDetail.getFacilitys();
        LinearLayout SheShigengduo = (LinearLayout)findViewById(R.id.homep_housedetail_SheShigengduo);
        //加载更多
        SheShigengduo.setOnClickListener(this);
        ImageView icon = (ImageView) SheShigengduo.getChildAt(0);
        Bitmap bitmap = URL.twoCollect(this, R.drawable.icon_add, 32,32);
        icon.setImageBitmap(bitmap);
        if (facilitys.size()>=4) {
            for (int i = 0; i < 4; i++) {
                facility_HPHouseDetail facility_hpHouseDetail = facilitys.get(i);
                LinearLayout ll = (LinearLayout) mFacility.getChildAt(i);
                ImageView img = (ImageView) ll.getChildAt(0);
                Picasso.with(this).load(facility_hpHouseDetail.getIcon()).into(img);
                TextView name = (TextView) ll.getChildAt(1);
                name.setText(facility_hpHouseDetail.getName());
            }
        }else{
            for (int i = 0; i < facilitys.size(); i++) {
                facility_HPHouseDetail facility_hpHouseDetail = facilitys.get(i);
                LinearLayout ll = (LinearLayout) mFacility.getChildAt(i);
                ImageView img = (ImageView) ll.getChildAt(0);
                Picasso.with(this).load(facility_hpHouseDetail.getIcon()).into(img);
                TextView name = (TextView) ll.getChildAt(1);
                name.setText(facility_hpHouseDetail.getName());
            }
            for(int i=facilitys.size();i< 4;i++){
                LinearLayout ll = (LinearLayout) mFacility.getChildAt(i);
                ll.setVisibility(View.INVISIBLE);
            }
        }
        mTitle.setText(houseDetail.getR_info_title());
    }
    //百度地图
    public void SetMap(String Lat,String Lng){
        BaiduMap baiduMap = mMap.getMap();

        Double lat = new Double(Lat);
        Double lng = new Double(Lng);

        mPoint = new LatLng(lat, lng);
//            39.963175, 116.400244
        //定义Maker坐标点
//构建Marker图标
        BitmapDescriptor bitmap = BitmapDescriptorFactory
                .fromResource(R.drawable.icon_gcoding);
//构建MarkerOption，用于在地图上添加Marker
        OverlayOptions option = new MarkerOptions()
                .position(mPoint)
                .icon(bitmap);
//在地图上添加Marker，并显示
        baiduMap.addOverlay(option);
//            点击某个Marker将其作为地图原点
        MapStatusUpdate mapStatusUpdate = MapStatusUpdateFactory.newLatLng(mPoint);
        baiduMap.setMapStatus(mapStatusUpdate);
    }
    private void initView() {
        mExit = (ImageView) findViewById(R.id.exit);
        mPicList = (ViewPager) findViewById(R.id.homep_housedetail_picList);
        mPrice = (TextView) findViewById(R.id.homep_housedetail_price);
        mPicListNum = (TextView) findViewById(R.id.homep_housedetail_picListNum);
        mName = (TextView) findViewById(R.id.homep_housedetail_name);
        mAddress = (TextView) findViewById(R.id.homep_housedetail_address);
        mOwner_name = (TextView) findViewById(R.id.homep_housedetail_owner_name);
        mBathroom_num = (TextView) findViewById(R.id.homep_housedetail_bathroom_num);
        mMax_person = (TextView) findViewById(R.id.homep_housedetail_max_person);
        mBed_num = (TextView) findViewById(R.id.homep_housedetail_bed_num);
        mContact = (Button) findViewById(R.id.homep_housedetail_contact);
        mIntro = (TextView) findViewById(R.id.homep_housedetail_intro);
        mMoreIntro = (TextView) findViewById(R.id.homep_housedetail_MoreIntro);
        mOnePic = (ImageView) findViewById(R.id.homep_housedetail_onePic);
        //地图
        mMap = (MapView)findViewById(R.id.homep_housedetail_baiduMap);

        mChakanDay = (TextView) findViewById(R.id.homep_housedetail_chakanDay);
        mReserve_address = (TextView) findViewById(R.id.homep_housedetail_Reserve_address);
        mFangyuanCK = (TextView) findViewById(R.id.homep_housedetail_fangyuanCK);
        mCheck_time = (TextView) findViewById(R.id.homep_housedetail_check_time);
        mOut_time = (TextView) findViewById(R.id.homep_housedetail_out_time);
        mDeposit = (TextView) findViewById(R.id.homep_housedetail_deposit);
        mMin_Book_days = (TextView) findViewById(R.id.homep_housedetail_min_book_days);
        mMandateList = (ExpandListView) findViewById(R.id.homep_housedetail_mandate);
        mMandateList.setFocusable(false);
        mTwoPic = (ImageView) findViewById(R.id.homep_housedetail_twoPic);
        mFacility = (LinearLayout) findViewById(R.id.homep_housedetail_facility);
        mTitle = (TextView) findViewById(R.id.homep_housedetail_title);
        mDescription = (TextView) findViewById(R.id.homep_housedetail_description);

        //分享
        mShare = (ImageView) findViewById(R.id.homep_housedetail_share);
        initLisener();
    }
    private void initLisener(){
        mExit.setOnClickListener(this);
        mPicList.addOnPageChangeListener(this);
        mContact.setOnClickListener(this);
        mMoreIntro.setOnClickListener(this);
        mChakanDay.setOnClickListener(this);
        mFangyuanCK.setOnClickListener(this);
        mDescription.setOnClickListener(this);
        mShare.setOnClickListener(this);
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        mPicListNum.setText((position%picNum+1)+"/"+picNum);
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    @Override
    public void onClick(View view) {
        String [] data=null;
        String name=null;
        switch (view.getId()) {
            case R.id.exit://退出页面
                this.finish();
                break;
            case R.id.homep_housedetail_contact://联系店主

                break;
            case R.id.homep_housedetail_MoreIntro://查看更多
                data=new String[4];
                name="房间描述";
                data[0]=houseDetail.getIntro();
                data[1]=houseDetail.getRoom_inner_intro();
                data[2]=houseDetail.getTraffic_intro();
                data[3]=houseDetail.getAround_village_intro();
                showPopupWindow(1,name,data);
                break;
            case R.id.homep_housedetail_chakanDay://查看出租日历

                break;
            case R.id.homep_housedetail_fangyuanCK://查看房客守则
                data=new String[1];
                name="房间描述";
                data[0]=houseDetail.getUse_rule();
                showPopupWindow(1,name,data);
                break;
            case R.id.homep_housedetail_description://查看违约守则
                data=new String[1];
                name=houseDetail.getR_info_title();
                data[0]=houseDetail.getR_info_description();
                showPopupWindow(1,name,data);
                break;
            case R.id.homep_housedetail_SheShigengduo://更多
                name="配套设施";
                showPopupWindow(2,name,null);
                break;
            case R.id.ppexit://关闭PopupWindow
                mPopupWindow.dismiss();
                mPopupWindow=null;
                break;
            case R.id.pp_tvexit://关闭PopupWindow
                mPopupWindow.dismiss();
                mPopupWindow=null;
                break;
            case R.id.ppexit2://关闭PopupWindow
                mPopupWindow.dismiss();
                mPopupWindow=null;
                break;
            case R.id.pp_tvexit2://关闭PopupWindow
                mPopupWindow.dismiss();
                mPopupWindow=null;
                break;
            //TODO 分享
            case R.id.homep_housedetail_share://分享
                showShare();
                break;


        }
    }
    public void showPopupWindow(int type,String name,String[] data){
        View contentView=null;
        if (type==1) {
            contentView= LayoutInflater.from(House_Detail_Activity.this).inflate(R.layout.more_popupwindow,null);
            ExpandListView listView= (ExpandListView) contentView.findViewById(R.id.content);
            ArrayAdapter adapter=new ArrayAdapter(this,R.layout.item_popupwindow,R.id.item_text,data);
            listView.setAdapter(adapter);
            ImageView exit= (ImageView) contentView.findViewById(R.id.ppexit);
            exit.setOnClickListener(this);
            TextView tvexit = (TextView) contentView.findViewById(R.id.pp_tvexit);
            tvexit.setOnClickListener(this);
            //更换title
            TextView title= (TextView) contentView.findViewById(R.id.titel);
            title.setText(name);
        }else if (type==2){
            contentView= LayoutInflater.from(House_Detail_Activity.this).inflate(R.layout.more_popupwindow2,null);
            GView gridView= (GView) contentView.findViewById(R.id.content2);
            PopupWindowAdapter adapter = new PopupWindowAdapter(this,houseDetail.getFacilitys());
            gridView.setAdapter(adapter);
            ImageView exit2= (ImageView) contentView.findViewById(R.id.ppexit2);
            exit2.setOnClickListener(this);
            TextView tvexit2 = (TextView) contentView.findViewById(R.id.pp_tvexit2);
            tvexit2.setOnClickListener(this);
            //更换title
            TextView title= (TextView) contentView.findViewById(R.id.titel);
            title.setText(name);
        }

        View rootView=LayoutInflater.from(House_Detail_Activity.this).inflate(R.layout.activity_house__detail_,null);

            mPopupWindow = new PopupWindow(contentView, 600, ViewPager.LayoutParams.WRAP_CONTENT);
            mPopupWindow.setContentView(contentView);
            mPopupWindow.setFocusable(true);
            mPopupWindow.setOutsideTouchable(true);
            mPopupWindow.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.colorWhite)));
            mPopupWindow.showAtLocation(rootView,Gravity.CENTER_VERTICAL,0,0);


    }

    private void showShare() {

        //TODO 已经拿到Application中初始化了
//        ShareSDK.initSDK(this);
        OnekeyShare oks = new OnekeyShare();
        //关闭sso授权
        oks.disableSSOWhenAuthorize();

// 分享时Notification的图标和文字  2.5.9以后的版本不调用此方法
        //oks.setNotification(R.drawable.ic_launcher, getString(R.string.app_name));
        // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
        oks.setTitle("第一出行");
        // titleUrl是标题的网络链接，仅在人人网和QQ空间使用
        oks.setTitleUrl("http://sharesdk.cn");
        // text是分享文本，所有平台都需要这个字段
        oks.setText("我是分享文本");
        // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
        //oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
        // url仅在微信（包括好友和朋友圈）中使用
        oks.setUrl("http://sharesdk.cn");
        // comment是我对这条分享的评论，仅在人人网和QQ空间使用
        oks.setComment("我是测试评论文本");
        // site是分享此内容的网站名称，仅在QQ空间使用
        oks.setSite(getString(R.string.app_name));
        // siteUrl是分享此内容的网站地址，仅在QQ空间使用
        oks.setSiteUrl("http://sharesdk.cn");

// 启动分享GUI
        oks.show(this);
    }
    /**
     *
     * @author xiaanming
     *
     */
    class MyAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            return Integer.MAX_VALUE;
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == arg1;
        }

        @Override
        public void destroyItem(View container, int position, Object object) {
            ((ViewPager)container).removeView(mImageViews[position % mImageViews.length]);

        }

        /**
         * 载入图片进去，用当前的position 除以 图片数组长度取余数是关键
         */
        @Override
        public Object instantiateItem(View container, int position) {
            ((ViewPager)container).addView(mImageViews[position % mImageViews.length], 0);
            return mImageViews[position % mImageViews.length];
        }



    }
}
